""" Take balance -) """

def _4balanse_in(l, r, r2):
    for i in l:
        if i[0] == r and float(i[3]) == float(r2):
            return True
    return False

def _4balanse_merge(l, r):
    for i in l:
        if i[0] == r[0]:
            i[2] = int(i[2]) + int(r[2])
            return 

def balance(income, outcome):
    income_title = income[0]
    outcome_title = outcome[0]
    income.remove(income_title)
    outcome.remove(outcome_title)

    for i in outcome:
        i[2] = int(i[2]) * (-1)
    income.extend(outcome)

    t_income = []
    for i in income:
        if _4balanse_in(t_income, i[0], i[3]): 
            _4balanse_merge(t_income, i)
        else: 
            t_income.append(i)

    return t_income

if __name__ == '__main__':
    income = [
    ['reference', 'provider', 'count', 'price', 'date'],
    ['11', '5', '10', '10', '20081030'],
    ['12', '6', '13', '100.0', '20081030'],
    ['12', '6', '1', '100.0', '20081117'],
    ['1', '5', '11', '11.44', '20081117'],
    ['2', '5', '1110', '112.0', '20081118'],
    ]
    outcome = [
    ['reference', 'recipient', 'count', 'price', 'date'],
    ['1', '2', '1', '10.0', '20081030'],
    ['1', '1', '3', '10.0', '20081030'],
    ['12', '1', '11', '100.0', '20081117'],
    ['2', '4', '1000', '112.0', '20081118'],
    ]    

    for t in balance(income, outcome):
        print t


